#include "pch.hpp"
#include "TaskModel.hpp"

using namespace services;




TaskModel::TaskModel(scheduler::ptr s, QObject* parent)
	: QAbstractTableModel(parent)
	, m_scheduler(s)
{}
///////////////////////////////////////////////////////////////////////////////////////////////////




void TaskModel::update()
{
	auto tasks = m_scheduler->tasks();

	// The number of tasks that the current and the next model have in common
	// should merely be requeried from the view
	std::size_t numUpdateTasks = std::min(tasks.size(), m_tasks.size());
	auto in = tasks.begin();
	auto out = m_tasks.begin();

	if(numUpdateTasks != 0)
	{
		// Copy that section into the current tasks and then emit the signal
		for(; in != tasks.end() && out != m_tasks.end(); ++in, ++out)
		{
			using namespace std;
			swap(*out, *in);
		}

		emit dataChanged(index(0, 0), index(numUpdateTasks - 1, columnCount() - 1));
	}

	// If there are more tasks than before, then we add rows, otherwise we remove them
	std::size_t newTasks = tasks.size() > m_tasks.size() ? tasks.size() - m_tasks.size() : 0;
	std::size_t remTasks = tasks.size() < m_tasks.size() ? m_tasks.size() - tasks.size() : 0;
	if(newTasks > 0)
	{
		beginInsertRows(QModelIndex(), numUpdateTasks, numUpdateTasks + newTasks);
		// Copy the remaining bit into the new tasks
		std::copy(in, tasks.end(), out);

		endInsertRows();
	}
	else if(remTasks > 0)
	{
		
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////




int TaskModel::rowCount(const QModelIndex& parent) const
{
	return m_tasks.size();
}
///////////////////////////////////////////////////////////////////////////////////////////////////

int TaskModel::columnCount(const QModelIndex& parent) const
{
	return 3;
}
///////////////////////////////////////////////////////////////////////////////////////////////////

QVariant TaskModel::headerData(int section, Qt::Orientation orientation, int role) const
{
	switch(orientation)
	{
	case Qt::Vertical:   return section + 1;
	case Qt::Horizontal:
		switch(role)
		{
		case Qt::DisplayRole:
			switch(section)
			{
			case 0: return "Looped";
			case 1: return "Dedicated";
			case 2: return "Progress";
			}
			break;
		}
	}

	return QVariant();
}
///////////////////////////////////////////////////////////////////////////////////////////////////

QVariant TaskModel::data(const QModelIndex& index, int role) const
{
	if(index.row() >= rowCount())
		return QVariant();

	const task::const_ptr& t = m_tasks[index.row()];

	switch(role)
	{
	case Qt::DisplayRole:
		switch(index.column())
		{
		case 0: return t->dedicated() ? "Yes" : "No";
		case 1: return t->looped() ? "Yes" : "No";
		case 2: return QString("%1%").arg(t->progress() * 100.0f);
		}
		break;
	}

	return QVariant();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
